

layui.use(['table', 'admin', 'ax', 'form', 'layer'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var layer = layui.layer;



    var arrId = [];

    var selectId=[];

//监听表格复选框选择
    table.on('checkbox(goodsTable)', function(obj){
        var id  = obj.data.id;
        var isChecked = obj.checked;
        if(!id&&isChecked) {
            selectId = arrId;
        }else if(!id&&!isChecked){
            selectId = []
        }else if(id&&isChecked){ // 单行选择&&选中
               var r = selectId.indexOf(id)>-1;
                !r&&selectId.push(id)
        }else{// 单行选择&&取消
            var r = selectId.indexOf(id)>-1;
            for(var i =0;i<selectId.length;i++){
                r&&selectId.splice(i,1);
            }
        }
        console.log(selectId)
    });




    /**
     * 批量上架
     */
    $('#batchShelves').click(function () {

        var arr_box = "";

        for(var i =0;i<selectId.length;i++){
            arr_box += selectId[i] +",";
        }

        console.log(arr_box);

        $(function(){
            $.ajax({
                "url": Feng.ctxPath + "/goods/updateBatchShelves",
                "type":"post",
                "data" : {"id" : arr_box},
                "dataType":"json",
                "success":coolBack
            });
        });

        function coolBack(data){
            if(data.code == 200){
                Feng.success("批量上架成功！");
                window.location.reload()
            }else{
                Feng.error("批量上架失败！");
                window.location.reload()
            }
        }
    });



    /**
     * 批量下架
     */
    $('#batchOffTheShelf').click(function () {

        var arr_box = "";

        for(var i =0;i<selectId.length;i++){
            arr_box += selectId[i] +",";
        }

        console.log(arr_box);

            $(function(){
                $.ajax({
                    "url": Feng.ctxPath + "/goods/updateBatchOffTheShelf",
                    "type":"post",
                    "data" : {"id" : arr_box},
                    "dataType":"json",
                    "success":coolBack
                });
            });

            function coolBack(data){
                if(data.code == 200){
                    Feng.success("批量下架成功！");
                    window.location.reload()
                }else{
                    Feng.error("批量下架失败！");
                    window.location.reload()
                }
            }
    });



    /**
     * 商品表管理
     */
    var Goods = {
        tableId: "goodsTable"
    };

    /**
     * 初始化表格的列
     */
    Goods.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'id'},
            {
                field: 'goodsPic', sort: true, title: '图片', width: '10%', templet: function (d) {
                    if (d.goodsPic != null && d.goodsPic != "") {
                        return '<img src="' + d.goodsPic + '">';
                    } else {
                        return '<span>图片未上传</span>';
                    }
                }
            },

            {
                field: 'goodsPics' , sort: true, title: '多图展示', templet: function (d) {
                    if (d.goodsPics != null && d.goodsPics != "") {
                        var html = "";
                        var imgs = d.goodsPics.split(",");
                        for (var i = 0; i < imgs.length; i++) {
                            if(imgs[i]){
                                html = html + '<img alt="image" id="images" style="width: 50px;height: 50px;display: inline" class="img-responsive" onclick="show_img(\'' + imgs[i] + '\')"  src="' + imgs[i] + '">'
                            }
                        }
                        return html;
                    } else {
                        return '<span>图片未上传</span>';
                    }
                }
            },
            {
                field: 'goodsDetails', sort: true, title: '商品详情'},
            {field: 'brandsName', sort: true, title: '品牌分类'},
            {field: 'fullname', sort: true, title: '商品全称'},
            {field: 'name', sort: true, title: '商品简称'},
            {field: 'price', sort: true, title: '售价'},
            {field: 'area', sort: true, title: '产地'},
            {field: 'standard', sort: true, title: '规格'},
            {field: 'state', sort: true, title: '是否上架', templet: '#statusTpls'},
            //{field: 'integralState', sort: true, title: '积分商品', templet: '#statusTplss'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };
    /**
     * 点击查询按钮
     */
    Goods.search = function () {
        var queryData = {};
        queryData['usercode'] = $("#condition").val();
        queryData['fullname'] = $("#condition").val();
        queryData['name'] = $("#condition").val();
        table.reload(Goods.tableId, {
            where: queryData, page: {curr: 1}
        });
    };


    /**
     * 跳转到上传图文和视频页面中
     */
    Goods.pictureVideo = function (data) {
        window.location.href = Feng.ctxPath + '/goods/pictureVideoHtml?id=' + data.id;
    };


    /**
     * 弹出添加对话框
     */
    Goods.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/goods/add';
    };

    /**
     * 导出excel按钮
     */
    Goods.exportExcel = function () {
        var checkRows = table.checkStatus(Goods.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    Goods.syncGoods = function () {
        var loading = layer.msg('正在同步', {icon: 16, shade: 0.3, time: 0});
        $.ajax({
            url: Feng.ctxPath + "/taoStock/getGoodsByYesterdayOnePrice",
            success: function (data) {
                layer.close(loading);
                if (data.code == 200 || data.code == "200") {
                    Feng.success("同步成功!");
                    table.reload(Goods.tableId);
                } else {
                    Feng.success("同步异常!");
                    table.reload(Goods.tableId);
                }
            }
        });
    }

    Goods.UpDates = function () {
        var loading = layer.msg('正在上载', {icon: 16, shade: 0.3, time: 0});
        $.ajax({
            url: Feng.ctxPath + "/taoStock/uploadGoods",
            success: function (data) {
                layer.close(loading);
                if (data.code == 200 || data.code == "200") {
                    Feng.success("上载成功!");
                    table.reload(Goods.tableId);
                } else {
                    Feng.success("上载异常!");
                    table.reload(Goods.tableId);
                }
            }
        });
    }

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    Goods.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/goods/edit?id=' + data.id;
    };


    Goods.onDetail = function (data) {
        window.location.href = Feng.ctxPath + '/goods/details?ptypeid=' + data.id;
    };

    /**
     * 添加热门商品
     *
     * @param data 点击按钮时候的行数据
     */
    Goods.addHotGood = function (data) {
        var goodId = data.usercode;
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/taoIndexPic/addItem?goodId="+goodId, function (data) {
                Feng.success("添加成功!");
                table.reload(Goods.tableId);
            }, function (data) {
                Feng.error("添加失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("确认添加?", operation);
    };

    /**
     * 添加首页推荐产品
     *
     * @param data 点击按钮时候的行数据
     */
    Goods.addRecommend = function (data) {
        var goodId = data.id;
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/taoRecommendGoods/addGoods?goodId="+goodId, function (data) {
                Feng.success("添加成功!");
                table.reload(Goods.tableId);
            }, function (data) {
                Feng.error("添加失败!" + data.responseJSON.message + "!");
            });
            ajax.set("goodId", data.goodId);
            ajax.start();
        };
        Feng.confirm("确认添加?", operation);
    };

    /**
     * 添加种草
     */
    Goods.addsRecommend = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/sRecommend/addItem?id="+data.id, function (data) {
                Feng.success("添加种草成功!");
                table.reload(Goods.tableId);
            }, function (data) {
                Feng.error("添加失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否把商品添加到种草?", operation);
    };




    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    Goods.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/goods/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(Goods.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Goods.tableId,
        url: Feng.ctxPath + '/goods/list',
        page: true,
        height: "full-158",
        cellMinWidth: 100,
        cols: Goods.initColumn(),
        done:function(res){
            var r=res.data
            var arr = []
            for(var  i=0;i<r.length;i++){
               arr.push(r[i].id);
            }
            arrId = arr;
        },
        response: {
            statusName: 'code' //规定数据状态的字段名称，默认：code
            , statusCode: 0 //规定成功的状态码，默认：0
            , msgName: 'msg' //规定状态信息的字段名称，默认：msg
            , countName: 'count' //规定数据总数的字段名称，默认：count
            , dataName: 'data' //规定数据列表的字段名称，默认：data
        }
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Goods.search();
    });

    // 添加按钮点击事件
    $('#btnUpDate').click(function () {
        Goods.UpDates();
    });

    // 导出excel
    $('#btnSync').click(function () {
        Goods.syncGoods();
    });

    // 工具条点击事件
    table.on('tool(' + Goods.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Goods.openEditDlg(data);
        } else if (layEvent === 'delete') {
            Goods.onDeleteItem(data);
        } else if (layEvent === 'detail') {
            Goods.onDetail(data);
        }else if (layEvent === 'addHotGood') {
            Goods.addHotGood(data);
        }else if (layEvent === 'pictureVideo'){
            Goods.pictureVideo(data);
        }else if (layEvent == 'addsRecommend'){
            Goods.addsRecommend(data);
        }else if (layEvent == 'addRecommend'){
            Goods.addRecommend(data);
        }
    });

    /**
     * 修改状态
     *
     * @param userId 用户id
     * @param checked 是否选中（true,false），选中就是解锁用户，未选中就是锁定用户
     */
    Goods.changeState = function (userId, checked) {
        if (checked == 1) {
            var ajax = new $ax(Feng.ctxPath + "/goods/editItem", function (data) {
                Feng.success("上架成功!");
            }, function (data) {
                Feng.error("上架失败!");
                table.reload(Goods.tableId);
            });
            ajax.set("id", userId);
            ajax.set("state", 1);
            ajax.start();
        } else if (checked == 2) {
            var ajax = new $ax(Feng.ctxPath + "/goods/editItem", function (data) {
                Feng.success("下架成功！");
            }, function (data) {
                Feng.error("下架失败!" + data.responseJSON.message + "!");
                table.reload(Goods.tableId);
            });
            ajax.set("id", userId);
            ajax.set("state", 2);
            ajax.start();
        }
    };
    Goods.changeStates = function (userId, checked) {
        if (checked == 1) {
            var ajax = new $ax(Feng.ctxPath + "/goods/editItem", function (data) {
                Feng.success("开启成功!");
            }, function (data) {
                Feng.error("开启失败!");
                table.reload(Goods.tableId);
            });
            ajax.set("id", userId);
            ajax.set("integralState", 1);
            ajax.start();
        } else if (checked == 0) {
            var ajax = new $ax(Feng.ctxPath + "/goods/editItem", function (data) {
                Feng.success("关闭成功！");
            }, function (data) {
                Feng.error("关闭失败!" + data.responseJSON.message + "!");
                table.reload(Goods.tableId);
            });
            ajax.set("id", userId);
            ajax.set("integralState", 0);
            ajax.start();
        }
    };


    // 修改状态
    form.on('switch(status)', function (obj) {

        var userId = obj.elem.value;
        var checked = obj.elem.checked ? 1 : 2;

        Goods.changeState(userId, checked);
    });

    // 修改积分状态
    form.on('switch(statuss)', function (obj) {
        var userId = obj.elem.value;
        var checked = obj.elem.checked ? 1 : 0;

        Goods.changeStates(userId, checked);
    });
});

function show_img(t) {
    //页面层
    layer.open({
        type: 1,
        area: ['50%', '50%'], //宽高
        title: false,
        shadeClose: true, //开启遮罩关闭
        end: function (index, layero) {
            return false;
        },
        content: "<img style='width: 100%' src='" + t + "'/>"
    });

}











